package com.jz.banner.screen.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.Nullable
import androidx.core.content.ContextCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.viewpager.widget.ViewPager
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener
import com.google.gson.Gson
import com.jz.banner.screen.R
import com.jz.banner.screen.bean.BaseData
import com.jz.banner.screen.bean.UpdateInfo
import com.jz.banner.screen.ui.App
import com.jz.banner.screen.utils.Urls.SIGN_UPDATE_TYPE_BY_SHELL_INSTALL_JGL
import com.youth.banner.Transformer
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.Locale.getDefault
import java.util.regex.Pattern


/**
 * 创建者     Noel
 * 创建时间   2017/12/21 9:23
 * 描述	      工具类
 */

const val REQUEST_CODE_SCANNER_ENTERPRISE_DETAILS = 1001


class CommUtils {

    companion object {
        private val len = 1800
        private var tag = "CommUtils"
        var MATCH_PARENT = -1
        var WRAP_CONTENT = -2
        val gson: Gson by lazy { Gson() }

        fun println(tag: String? = null, msg: String) {
            // this.tag = tag
            var tmp = tag ?: this.tag
            if (App.isDebug) {
                if (msg.length > len) {
                    //kotlin.io.println(show)
                    kotlin.io.println(tmp + msg.substring(0, len))
                    if ((msg.length - len) > len) { //剩下的文本还是大于规定长度
                        println(msg.substring(len, msg.length))
                    } else {
                        kotlin.io.println(tmp + msg.substring(len, msg.length))
                    }
                } else {
                    kotlin.io.println(tmp + msg)
                }
            }

        }

        fun dp2px(dpValue: Float): Int {
            val density = App.context!!.resources.displayMetrics.density
            return (density * dpValue + 0.5).toInt()
        }

        fun dp2px(dpValue: Int): Int {
            val density = App.context!!.resources.displayMetrics.density
            return (density * dpValue + 0.5).toInt()
        }

        fun dp2pxF(dpValue: Float): Float {
            val density = App.context!!.resources.displayMetrics.density
            return density * dpValue
        }

        fun px2dip(pxValue: Float): Int {
            val scale = App.context!!.resources.displayMetrics.density
            return (pxValue / scale + 0.5f).toInt()
        }

        fun sp2px(sp: Int): Int {
            return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), App.context!!.resources.displayMetrics
            )
                .toInt()
        }

        fun sp2pxF(sp: Int): Float {
            return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), App.context!!.resources.displayMetrics
            )
        }

        /**
         * method is used for checking valid email id formatDate.
         * @param email
         * @return boolean true for valid false for invalid
         */
        fun isEmailValid(email: String): Boolean {
            var isValid = false
            val expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"

            val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
            val matcher = pattern.matcher(email)
            if (matcher.matches()) {
                isValid = true
            }
            return isValid
        }


        fun creatItemView(context: Context, layout: Int, w: Int, h: Int): View {
            val view = View.inflate(context, layout, null)
            view.layoutParams = DrawerLayout.LayoutParams(w, h)
            return view
        }

        //获取设备号
        fun getAppUUid(): String {
//            var uuid = SPUtils.getString("PREF_KEY_UUID")
//            if (uuid.isNullOrBlank()) {
//                uuid = UUID.randomUUID().toString().toUpperCase(Locale.ROOT)//.substring(0,8)
//                SPUtils.putString("PREF_KEY_UUID", uuid)
//            }
            return UniqueIDUtils.getUniqueID().toUpperCase(Locale.getDefault())
        }

        /**
         * 获取App版本码
         *
         * @return App版本码
         */
        fun getAppVersionCode(): Int {
            return getAppVersionCode(App.context!!, App.context!!.packageName)
        }

        /**
         * 获取App版本码
         *
         * @param context     上下文
         * @param packageName 包名
         * @return App版本码
         */
        fun getAppVersionCode(context: Context, packageName: String): Int {
            if (TextUtils.isEmpty(packageName)) {
                return -1
            }
            return try {
                val pm = context.packageManager
                val pi = pm.getPackageInfo(packageName, 0)
                pi?.versionCode
                    ?: -1
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                -1
            }

        }

        /**
         * 返回当前程序版本名称
         */
        fun getAppVersionName(): String {
            return try {
                // Get the package info
                var pm = App.context!!.packageManager
                var pi = pm.getPackageInfo(App.context!!.packageName, 0)
                pi.versionName.plus("::").plus(getAppUUidLast4())
                    ?: "空版本 for Android"
            } catch (e: Exception) {
                "未知版本好 for Android"
            }
        }

        //获取设备号后四位
        fun getAppUUidLast4(): String {
            val appUUid = getAppUUid()
            val subUUid = appUUid.substring(0, 4)
            println("getAppUUidLast4:", "appUUid:$appUUid,subUUid:$subUUid")
            return subUUid
        }


        fun toYMD(ms: Long?, pattern: String = "yyyy-MM-dd"): String {
            return try {
                if (ms!! == 0L) return ""
                var data = Date(ms * 1000)
                SimpleDateFormat(pattern, getDefault()).format(data)
            } catch (e: Exception) {
                ""
            }
        }

        fun toYMDHM(ms: Long?): String {
            return try {
                if (ms!! == 0L) return ""
                var data = Date(ms * 1000)
                SimpleDateFormat("yyyy-MM-dd HH:mm", getDefault()).format(data)
            } catch (e: Exception) {
                ""
            }
        }

        @SuppressLint("SimpleDateFormat")
        //年月日 转 秒
        fun YMD2s(ymd: String?, pattern: String = "yyyyMMdd"): Long? {
            return try {
                if (ymd == null) null
                else {
                    val simpleDateFormat = SimpleDateFormat(pattern)
                    simpleDateFormat.parse(ymd).time / 1000
                }
            } catch (e: Exception) {
                null
            }
        }

        val df: DecimalFormat by lazy { DecimalFormat(".##") }
        fun save2floatNoZero(float: Float): Float {
            return df.format(float)
                .toFloat()
        }

        fun float2Str(float: Float?): String {
            return try {
                float.toString()
            } catch (e: Exception) {
                "0"
            }
        }

        fun encodeByMD5(text: String): String {
            try {
                //获取md5加密对象
                val instance: MessageDigest = MessageDigest.getInstance("MD5")
                //对字符串加密，返回字节数组
                val digest: ByteArray = instance.digest(text.toByteArray())
                var sb: StringBuffer = StringBuffer()
                for (b in digest) {
                    //获取低八位有效值
                    var i: Int = b.toInt() and 0xff
                    //将整数转化为16进制
                    var hexString = Integer.toHexString(i)
                    if (hexString.length < 2) {
                        //如果是一位的话，补0
                        hexString = "0$hexString"
                    }
                    sb.append(hexString)
                }
                return sb.toString()
                    .apply { CommUtils.println("sign", "MD5后：$this") }

            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
            }
            return ""
        }


        //设置边距margin
        fun setMargins(v: View?, l: Int, t: Int, r: Int, b: Int) {
            if (v?.layoutParams is ViewGroup.MarginLayoutParams) {
                val p = v.layoutParams as ViewGroup.MarginLayoutParams
                p.setMargins(dp2px(l), dp2px(t), dp2px(r), dp2px(b))
                v.requestLayout()
            }
        }

        fun setHeight(v: View?, height: Int) {
            if (v?.layoutParams is ViewGroup.MarginLayoutParams) {
                val p = v.layoutParams as ViewGroup.MarginLayoutParams
                p.height = 0
                v.requestLayout()
            }
        }

        fun isConnectingToInternet(): Boolean {
            var connectivity =
                App.context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                var networks = connectivity.allNetworks
                var networkInfo: NetworkInfo
                for (mNetwork in networks) {
                    networkInfo = connectivity.getNetworkInfo(mNetwork);
                    if (networkInfo.state == NetworkInfo.State.CONNECTED) {
                        return true
                    }
                }
            } else {
                var info = connectivity.allNetworkInfo
                if (info != null)
                    for (i in 0..info.size) {
                        if (info[i].state == NetworkInfo.State.CONNECTED) {
                            return true
                        }
                    }
            }
            return false
        }

        fun getBannerAnimation(type: Int): Class<out ViewPager.PageTransformer>? {
            return when (type) {
                0 -> Transformer.Default
                1 -> Transformer.Accordion
                2 -> Transformer.BackgroundToForeground
                3 -> Transformer.ForegroundToBackground
                4 -> Transformer.CubeIn
                5 -> Transformer.CubeOut
                6 -> Transformer.DepthPage
                7 -> Transformer.FlipHorizontal
                8 -> Transformer.FlipVertical
                9 -> Transformer.RotateDown
                10 -> Transformer.RotateUp
                11 -> Transformer.ScaleInOut
                12 -> Transformer.Stack
                13 -> Transformer.Tablet
                14 -> Transformer.ZoomIn
                15 -> Transformer.ZoomOutSlide
                16 -> Transformer.ZoomOut
                else -> getBannerAnimation(Random().nextInt(16))
            }
        }

        fun checkUpdateApp(run: Runnable = Runnable { }) {
            AllenVersionChecker.getInstance().cancelAllMission()
            var update = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestUrl(Urls.apkCheckUpdateUrl)
                .request(object : RequestVersionListener {
                    @Nullable
                    override fun onRequestVersionSuccess(downloadBuilder: DownloadBuilder?, result: String?): UIData? {
                        var data = try {
                            gson.fromJson<UpdateInfo>(result, UpdateInfo::class.java)?.data
                        } catch (e: Exception) {
                            UpdateInfo()
                        }
                        Urls.initUrl(data?.BaseUrl, data?.BaseImgUrl)
                        when (Urls.updateType) {
                            SIGN_UPDATE_TYPE_BY_SHELL_INSTALL_JGL -> {
                                return if (getAppVersionCode() < data?.signVersionJgl?.versionCode ?: 1) {
                                    UIData.create()
                                        .setDownloadUrl(data?.signVersionJgl?.url)
                                } else {
                                    //自动登录
                                    run.run()
                                    null
                                }
                            }
                            else -> {
                                return if (getAppVersionCode() < data?.versionCode ?: 1) {
                                    UIData.create()
                                        .setDownloadUrl(data?.url)
                                } else {
                                    //自动登录
                                    run.run()
                                    null
                                }
                            }
                        }
                    }

                    override fun onRequestVersionFailure(message: String) {
                        run.run()
                    }
                })
                .setDownloadAPKPath(ApkHelper.getDownloadApkCachePath())
                .setApkName(App.context!!.getString(R.string.app_name))
                .setDirectDownload(true)
                .setShowNotification(true)
                .setShowDownloadingDialog(true)
                .setShowDownloadFailDialog(true)
                .setForceRedownload(false)
            when (Urls.updateType) {
                Urls.NOT_SIGN_UPDATE_TYPE_BY_SHELL_INSTALL, SIGN_UPDATE_TYPE_BY_SHELL_INSTALL_JGL -> {
                    //android 6板
                    update.setCustomDownloadInstallListener { context, apk ->
                        ShellUtils.execAutoRoot("/system/bin/pm install -r " + apk.path)
                    }.executeMission(App.context)
                }
                Urls.NOT_SIGN_UPDATE_TYPE_BY_ANDROID_CODE_INSTALL -> {
//                    update.setCustomDownloadInstallListener { context, apk ->
//                        //android 5板
//                        var intent = Intent(Intent.ACTION_VIEW)
//                        intent.setDataAndType(apk, "application/vnd.android.package-archive")
//                        intent.putExtra("IMPLUS_INSTALL", "SILENT_INSTALL")
//                        activity.startActivity(intent)
//                    }.executeMission(App.context)
                    update.executeMission(App.context)
                }
                else -> {
                    update.executeMission(App.context)
                }
            }
        }


    }


}


//扩展方法。去颜色
fun Any?.getColor(ids: Int): Int = ContextCompat.getColor(App.context!!, ids)

fun String?.toThumb(): String? {
    return try {
        var frontStr = this!!.substring(0, this.indexOfLast { it == '.' })
        var laterStr = substring(this.indexOfLast { it == '.' }, this.length)
        frontStr.plus("_thumb")
            .plus(laterStr)
            .apply {
                CommUtils.println("toThumb:", "frontStr:$frontStr,laterStr:$laterStr,whole:$this")
            }
    } catch (e: Exception) {
        this
    }
}

fun String?.toImgList(): List<String> {
    return try {
        when {
            this == null -> emptyList()
            this.isBlank() -> emptyList()
            else -> this.split(",").toList()
        }
    } catch (e: Exception) {
        emptyList()
    }
}

fun String?.str2Double(): Double {
    return try {
        this!!.toDouble()
    } catch (e: Exception) {
        0.0
    }
}

/*
* isIgnoreBlank: 是否忽略空白，是就当有空白也会以逗号分隔。
* */
fun List<String>?.toImgUrl(isIgnoreBlank: Boolean = false): String {
    return try {
        var str = StringBuffer().apply sb@{
            this@toImgUrl!!.forEach {
                when {
                    isIgnoreBlank -> append(it).append(",")
                    it.isNotBlank() -> append(it).append(",")
                }
            }
        }
            .toString()
        if (str.isNotEmpty()) {
            str.substring(0, str.length - 1)
        } else ""
    } catch (e: Exception) {
        ""
    }
}

/*判断字符串 true: 空和0 */
fun String?.isNullOrZero(): Boolean {
    return try {
        this == null || this.isBlank() || this.toInt() == 0
    } catch (e: Exception) {
        false
    }
}

/*如果是null或者blank则返回 无*/
fun String?.isMo(): String {
    return if (this.isNullOrBlank()) "无" else this!!
}


/*判断字符串 为空返回“暂无”*/
fun String?.isNotAvailable(): String {
    return try {
        if (this == null || this.isBlank() || this.isEmpty()) "暂无" else this
    } catch (e: Exception) {
        "暂无"
    }
}

/*请求数据还会状态吗 等于1 就成功*/
fun BaseData.isGetDataSuccess(): Boolean {
    return when (code) {
        1 -> true
        else -> {
            ToastUtil.showToast(message)

            false
        }
    }
}

fun TextView.formatTimes(tiems: String?, suffixStr: String, proportion: Float = 1.5f) {
    try {
        var ss = SpannableString(tiems.plus(suffixStr))
        ss.setSpan(
            RelativeSizeSpan(proportion),
            0,
            tiems!!.length,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        ss.setSpan(StyleSpan(Typeface.BOLD), 0, tiems.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        this.text = ss
    } catch (e: Exception) {
        //var ss = SpannableString(0.toString().plus(suffixStr))
        //ss.setSpan(RelativeSizeSpan(1.2f), 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        this.text = tiems.plus(suffixStr)
    }
}


